# _*_ encoding: utf-8 _*_

import os
import re
import sys
import os.path
import aiohttp
import asyncio
import aiofiles
import requests
import pyperclip
import nest_asyncio
from lxml import etree

nest_asyncio.apply()


def conbine(title_name, type_case):
    title_new = title_name + "c"
    if type_case == 3:
        os.system(
            f'ffmpeg -i ../data/blibli/dows/{title_new}.mp4 -i ../data/blibli/dows/{title_new}.mp3 -c copy ../data/blibli/video/{title_name}.mp4')
    elif type_case == 1 or 2:
        print(
            f'ffmpeg -i ../data/blibli/dows/{title_new}.mp4 -i ../data/blibli/dows/{title_new}.mp3 -c copy ../data/blibli/up_zhu/{title_name}.mp4')
        os.system(
            f'ffmpeg -i ../data/blibli/dows/{title_new}.mp4 -i ../data/blibli/dows/{title_new}.mp3 -c copy ../data/blibli/up_zhu/{title_name}.mp4')


def delete(title_name):
    title_new = title_name + 'c'
    os.remove('../data/blibli/dows/' + title_new + '.mp4')
    os.remove('../data/blibli/dows/' + title_new + '.mp3')


async def download(i, url, title_name, headers2):
    title_new = title_name + "c"
    async with aiohttp.ClientSession(headers=headers2) as session:
        async with session.get(url) as resp:
            data = await resp.content.read()
            if i == 0:
                filename = f"../data/blibli/dows/{title_new}.mp4"

            elif i == 1:
                filename = f"../data/blibli/dows/{title_new}.mp3"
            try:
                async with aiofiles.open(filename, 'wb') as fp:
                    await fp.write(data)
            except Exception as e:
                print("aiofiles错误: %s" % e)


async def asyncmake(video_url, audio_url, title_name, headers2):
    urls = [video_url, audio_url]
    tasks = []
    for i in range(0, 2):
        print(f'.....................{i}.............................')
        d = asyncio.create_task(download(i, urls[i], title_name, headers2))
        tasks.append(d)
    await asyncio.wait(tasks)


def main():
    # 剪切板复制的内容
    url = str(pyperclip.paste())
    url = url if url else "https://www.bilibili.com/video/BV1gt4y1b7KX/?spm_id_from=333.337.search-card.all.click&vd_source=3d70e5e22ecd43622921eab591d77cd1"
    # 设置请求头参数
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
        "cookie": "buvid3=6A14510F-D568-4BD9-D5C6-AC7BC26843C497804infoc; b_nut=1663161697; i-wanna-go-back=-1; _uuid=AFA43BCC-E910D-F1CC-EEF6-297119410108A512509infoc; buvid4=CE4DA170-C4A7-E583-8FBB-791A74D295E599226-022091421-RiZ/oNmWCiFltsT47d+zIQ%3D%3D; rpdid=|(u)~mm)k~J~0J'uYYJuYu~u|; LIVE_BUVID=AUTO1416631617761539; buvid_fp_plain=undefined; b_ut=5; bp_video_offset_15769989=720929210206519300; fingerprint=fe700e9add6acbacb8be723c867fc0cf; DedeUserID=487341535; DedeUserID__ckMd5=91c3e31dc599efc3; buvid_fp=9cdb1216b00381986d2adf990f9dae91; PVID=1; bp_video_offset_487341535=720136943370764300; nostalgia_conf=-1; b_lsid=E88D6AEC_1844AA7EEE7; bsource=search_baidu; SESSDATA=7671d0a4%2C1683251836%2C8b6c1%2Ab1; bili_jct=ea9c3176888b689ac651d93b8ef4e8f0; innersign=1; CURRENT_FNVAL=16; sid=64n5qsjr",
        "referer": "https://search.bilibili.com/all?keyword=%E9%A3%8E%E6%99%AF%E8%A7%86%E9%A2%91%E7%B4%A0%E6%9D%90%20%E9%AB%98%E6%B8%85&from_source=webtop_search&spm_id_from=333.1007&search_source=2",
    }

    resp = requests.get(url, headers=headers)
    data = resp.text
    html_obj = etree.HTML(data)
    print(html_obj)
    print(" 1表示B站UP主视频\n 2表示up主选集视频\n 3表示电视剧类型")
    type_case = int(input("请输入下载的类型："))
    if type_case == 1:
        #
        title_name = html_obj.xpath('//*[@id="viewbox_report"]/h1/span/text()')[0]
        url_str = html_obj.xpath('/html/head/script[5]/text()')[0]
        video_url = re.findall(r'video":\[{"id":\d+,"baseUrl":"(.*?)"', url_str)[0]
        audio_url = re.findall(r'audio":\[{"id":\d+,"baseUrl":"(.*?)"', url_str)[0]

    elif type_case == 2:
        #
        title_name1 = html_obj.xpath('//*[@id="viewbox_report"]/h1/span/text()')[0]
        title_name2 = url.split('?')[1]
        title_name = title_name1 + title_name2
        url_str = html_obj.xpath('/html/head/script[5]/text()')[0]
        video_url = re.findall(r'video":\[{"id":\d+,"baseUrl":"(.*?)"', url_str)[0]
        audio_url = re.findall(r'audio":\[{"id":\d+,"baseUrl":"(.*?)"', url_str)[0]

    elif type_case == 3:
        title_name = html_obj.xpath("/html/head/title/text()")[0]
        title_name = title_name.split('_')[0]
        url_str = html_obj.xpath('/html/body/script[3]/text()')[0]
        video_url = \
        re.findall(r'video":\[{"start_with_sap":\d+,"bandwidth":\d+,"sar":"\d+:\d+","backupUrl":\["(.*?)"', url_str)[0]
        audio_url = \
        re.findall(r'audio":\[{"start_with_sap":\d+,"bandwidth":\d+,"sar":"","backupUrl":\["(.*?)"', url_str)[0]

    print(title_name + "正在下载中")
    header2 = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
        "referer": url,
    }

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncmake(video_url, audio_url, title_name, headers2))
    conbine(title_name, type_case)
    # delete(title_name)
    print("下载完成")


def download_by_video():
    url = input("请粘贴要下载的视频链接：")
    print(url)
    if not url:
        print("您没有输入url地址")
        sys.exit(0)
        # url = "https://www.bilibili.com/video/BV1gt4y1b7KX/?spm_id_from=333.337.search-card.all.click&vd_source=3d70e5e22ecd43622921eab591d77cd1"
        url = "https://www.bilibili.com/video/BV1TV4y1J7Zh/?spm_id_from=333.337.search-card.all.click&vd_source=3d70e5e22ecd43622921eab591d77cd1"
    # 设置请求头参数
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
        "cookie": "buvid3=6A14510F-D568-4BD9-D5C6-AC7BC26843C497804infoc; b_nut=1663161697; i-wanna-go-back=-1; _uuid=AFA43BCC-E910D-F1CC-EEF6-297119410108A512509infoc; buvid4=CE4DA170-C4A7-E583-8FBB-791A74D295E599226-022091421-RiZ/oNmWCiFltsT47d+zIQ%3D%3D; rpdid=|(u)~mm)k~J~0J'uYYJuYu~u|; LIVE_BUVID=AUTO1416631617761539; buvid_fp_plain=undefined; b_ut=5; bp_video_offset_15769989=720929210206519300; fingerprint=fe700e9add6acbacb8be723c867fc0cf; DedeUserID=487341535; DedeUserID__ckMd5=91c3e31dc599efc3; buvid_fp=9cdb1216b00381986d2adf990f9dae91; PVID=1; bp_video_offset_487341535=720136943370764300; nostalgia_conf=-1; b_lsid=E88D6AEC_1844AA7EEE7; bsource=search_baidu; SESSDATA=7671d0a4%2C1683251836%2C8b6c1%2Ab1; bili_jct=ea9c3176888b689ac651d93b8ef4e8f0; innersign=1; CURRENT_FNVAL=16; sid=64n5qsjr",
        "referer": "https://search.bilibili.com/all?keyword=%E9%A3%8E%E6%99%AF%E8%A7%86%E9%A2%91%E7%B4%A0%E6%9D%90%20%E9%AB%98%E6%B8%85&from_source=webtop_search&spm_id_from=333.1007&search_source=2",
    }
    headers2 = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
        "cookie": "buvid3=6A14510F-D568-4BD9-D5C6-AC7BC26843C497804infoc; b_nut=1663161697; i-wanna-go-back=-1; _uuid=AFA43BCC-E910D-F1CC-EEF6-297119410108A512509infoc; buvid4=CE4DA170-C4A7-E583-8FBB-791A74D295E599226-022091421-RiZ/oNmWCiFltsT47d+zIQ%3D%3D; rpdid=|(u)~mm)k~J~0J'uYYJuYu~u|; LIVE_BUVID=AUTO1416631617761539; buvid_fp_plain=undefined; b_ut=5; bp_video_offset_15769989=720929210206519300; fingerprint=fe700e9add6acbacb8be723c867fc0cf; DedeUserID=487341535; DedeUserID__ckMd5=91c3e31dc599efc3; buvid_fp=9cdb1216b00381986d2adf990f9dae91; PVID=1; bp_video_offset_487341535=720136943370764300; nostalgia_conf=-1; b_lsid=E88D6AEC_1844AA7EEE7; bsource=search_baidu; SESSDATA=7671d0a4%2C1683251836%2C8b6c1%2Ab1; bili_jct=ea9c3176888b689ac651d93b8ef4e8f0; innersign=1; CURRENT_FNVAL=16; sid=64n5qsjr",
        "referer": url,
    }
    resp = requests.get(url, headers=headers)
    data = resp.text
    html_obj = etree.HTML(data)
    title_name = html_obj.xpath('//*[@id="viewbox_report"]/h1/text()')[0]
    url_str = html_obj.xpath('/html/head/script[3]/text()')[0]
    video_url = re.findall(r'video":\[{"id":\d+,"baseUrl":"(.*?)"', url_str)[0]
    audio_url = re.findall(r'audio":\[{"id":\d+,"baseUrl":"(.*?)"', url_str)[0]
    print(title_name)
    print(video_url)
    print(audio_url)

    resp_video = requests.get(video_url, headers=headers2)
    resp_audio = requests.get(audio_url, headers=headers2)
    '''
    with open(f"E:/code/py/data/blibli/dows/{title_name}c.mp4",'wb') as f:
        f.write(resp_video.content)
    with open(f"E:/code/py/data/blibli/dows/{title_name}c.mp3",'wb') as f:
        f.write(resp_audio.content)
    '''
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncmake(video_url, audio_url, title_name, headers2))

    type_case = 1
    conbine(title_name, type_case)
    delete(title_name)
    print("下载完成")


if __name__ == "__main__":
    print(" 1批量下载\n 2单条解析下载")
    download_way = int(input("请输入："))
    if download_way == 1:
        main()
    elif download_way == 2:
        download_by_video()
